const util = require('../common/api_sign/request.js');

const getUsersig = async function(loginCallback) {
	
	// // #ifdef MP-WEIXIN
	// loginCallback?.(true)
	// return;
	// // #endif
	
	
	if (globalImIsSuccess) {
		loginCallback?.(true)
		return;
	}
	
	let that = this;
	const paramData = {};
	await util.request({
		url: '/plug/index.php?act=index&op=getIMUserSig',
		method: 'GET',
		data: {
			member_id: uni.getStorageSync("api_member_id")
		}
	}).then(res => {
		if (res.error_code == 0) {
			login(res.datas.identifier, res.datas.userSig, loginCallback);
		} else {
			loginCallback?.(false)
			uni.showToast({
				title: res.message,
				icon: 'none'
			});
		}
	})
}

const login = function(userID, userSig, loginCallback) {
	console.log(userID)
	const SDKAppID = getApp().globalData.sdkAppID;
	// #ifdef  APP-PLUS
	uni.$aegis.reportEvent({
		name: 'platform',
		ext1: 'platform-APP',
		ext2: 'uniTuikitExternal',
		ext3: `${SDKAppID}`
	});
	// #endif
	// #ifdef MP-WEIXIN
	uni.$aegis.reportEvent({
		name: 'platform',
		ext1: 'platform-MP-WEIXIN',
		ext2: 'uniTuikitExternal',
		ext3: `${SDKAppID}`
	});
	// #endif
	// #ifdef H5
	uni.$aegis.reportEvent({
		name: 'platform',
		ext1: 'platform-H5',
		ext2: 'uniTuikitExternal',
		ext3: `${SDKAppID}`
	});
	// #endif
	getApp().globalData.userInfo = {
		userSig,
		userID
	};
	// setTokenStorage({
	// 	userInfo: getApp().globalData.userInfo
	// });
	//wx.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);

	uni.$TUIKit.login({
			userID: userID,
			userSig: userSig
		})
		.then(() => {
			console.log('登录成功');
			console.log("loginEvent success")
			globalImIsSuccess = true
			loginCallback?.(true)
			
			uni.$aegis.reportEvent({
				name: 'login',
				ext1: 'login-success',
				ext2: 'uniTuikitExternal',
				ext3: `${SDKAppID}`
			});
		})
		.catch(error => {
			globalImIsSuccess = false			
			loginCallback?.(false)
			console.log("loginEvent", error)
			uni.$aegis.reportEvent({
				name: 'login',
				ext1: `login-failed#error:${error}`,
				ext2: 'uniTuikitExternal',
				ext3: `${SDKAppID}`
			});
		});

	// 登录原生插件
	// #ifdef APP-PLUS
	if (typeof uni.$TUICalling == 'undefined') {
		// uni.showToast({
		// 	title: '如果需要音视频功能，请集成插件使用真机运行并且自定义基座调试哦～',
		// 	icon: 'none',
		// 	duration: 3000
		// });
		// logger.error('请使用真机运行并且自定义基座调试，否则影响音视频功能～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use');
	} else {
		uni.$TUICalling.login({
				sdkAppID: SDKAppID,
				userID: userID,
				userSig: userSig
			},
			res => {
				console.log(JSON.stringify(res.msg));
				uni.showToast({
					title: 'login',
					icon: 'none'
				});
			}
		);
	}
	// #endif
}

let globalImIsSuccess = false;

module.exports = {
	getUsersig
}